<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { isNotEmpty, go2Link, isPhone, generateUUID, refresh } from '@/plugins/util.js'
import { useUser } from '@/composition/useUser'
import axios from 'axios'
import { useLocalStorage } from '@vueuse/core';
import Guide from '@/views/Guide.vue'
import Weather from '@/views/Weather.vue'


const { user } = useUser();

const searchHistory = useLocalStorage('searchHistory', []);


const favoShow = ref(false)
const editDialog = ref(false)
const bgImgUrl = ref('')
const searchFocus = ref(false)
const yiyanStr = ref('')
const logoShowType = ref('none')
const url = ref('')
const time = ref('')
const enterClass = ref('animated fadeInUp faster')
const leaveClass = ref('animated fadeOutDown faster')
const suggestion = ref([])
const searchEngineShow = ref(false)
const searchKey = ref('')
const isNeedShowSug = ref(false)
const searchInput = ref()

const suggestionShow = computed(() => {
    // 是否展示有3个条件，1.动画完成 2.需要展示 2.suggestion的长度大于0
    // console.log(searchengIsLeave.value)
    // console.log(isNeedShowSug.value)
    // console.log(suggestion.value)
    const userSearchInfoTmp = user.value.extInfo.search;
    return (userSearchInfoTmp.hisSwitch || userSearchInfoTmp.sugSwitch)
        && isNeedShowSug.value
        && suggestion.value.length > 0;

})

const searchForm = ref()
onMounted(() => {

    document.addEventListener("click", e => {
        if (searchForm.value && !searchForm.value.contains(e.target)) {
            inputBlur();
        }
    });

    init();
    getYiyan();
    setInterval(() => {
        let now = new Date();
        let hours = now.getHours() > 9 ? now.getHours() : '0' + now.getHours();
        let minutes = now.getMinutes() > 9 ? now.getMinutes() : '0' + now.getMinutes();
        // let seconds = now.getSeconds() > 9 ? now.getSeconds() : '0' + now.getSeconds();
        time.value = hours + ':' + minutes;
    }, 1000);
})

const getYiyan = () => {
    axios.get('https://v1.hitokoto.cn/')
        .then(function (response) {
            // 处理成功情况
            // console.log('response', response.data);
            yiyanStr.value = response.data.hitokoto + '  from~ ' + response.data.from;
        })
        .catch(function (error) {
            // 处理错误情况
            console.log('error', error);
        })
}

let searchEngineList;
let hisSwitch;
let sugSwitch;
const init = () => {
    let userSearchInfo = user.value.extInfo.search;
    // console.log('userSearchInfo:', userSearchInfo)
    searchEngineList = userSearchInfo.engines;
    hisSwitch = userSearchInfo.hisSwitch;
    sugSwitch = userSearchInfo.sugSwitch;
    const logo = user.value.extInfo.logo

    // 获取Logo
    logoShowType.value = logo.showType;
    logoShowType.value = 'time'
    url.value = logo.url;

    // 此处先写实，展示不支持设置
    // this.logoShowType = 'url';
    // this.url = 'https://www.ystel.cn/file/open/f0fb4bed6b664cfebbb30a688a4c8e3f/20201109/e1671b03783c4736899d7ad3debc4449.gif';
    // this.url = require("@/assets/logo1.png");

    // 更新 卡片的透明度
    // this.Utils.uCardStyle(this.openUserInfo.ext.cardTransparency || '2');
}
const ulMousedown = (event) => {
    // alert(1);
    let target = event.target;
    // console.log(target);
    if (target && target.preventDefault) {
        target.preventDefault();
    } else {
        window.event.returnValue = false;
    }
}
const clearSearchHis = () => {
    searchHistory.value = [];
    suggestion.value = [];
    searchInput.value.focus();
}
const getSug = () => {
    if (searchKey.value === '') {
        if (!hisSwitch) {
            return
        }
        suggestion.value = []
        // 从缓存中获取搜索的历史记录
        for (let i = 0; i < searchHistory.value.length; i++) {
            suggestion.value.push({
                uuid: generateUUID(),
                sug: searchHistory.value[i].word,
                orgSug: searchHistory.value[i].word,
                isHis: true
            });
        }
        // if (isPhone()) {
        //     suggestion.value.reverse();
        // }
    } else {
        if (!sugSwitch) {
            return
        }
        let url = 'https://suggestion.baidu.com/su?callback=sug&wd=' + searchKey.value + '&cb=sug&_=' + new Date().getTime();
        window.sug = (result) => {
            // console.log(result);
            suggestion.value = [];
            if (result && result.s && result.s.length > 0) {
                let data = result.s;
                let size = data.length > 6 ? 6 : data.length;
                for (let i = 0; i < size; i++) {
                    suggestion.value.push({
                        uuid: generateUUID(),
                        sug: data[i].replace(searchKey.value, '<b>' + searchKey.value + '</b>'),
                        orgSug: data[i]
                    });
                }
            }
            // if (isPhone()) {
            //     suggestion.value.reverse();
            // }
        }
        var JSONP = document.createElement("script");
        JSONP.type = "text/javascript";
        JSONP.src = `${url}&callback=sug`;
        document.getElementsByTagName("head")[0].appendChild(JSONP);
        setTimeout(() => {
            JSONP.remove();
        }, 500);
    }
}

const sugClick = (sug, searchFlag) => {
    // document.querySelector('#searchInput').focus();
    // this.searchKey = sug.replace('<b>', '').replace('</b>', '');
    if (searchFlag) {
        searchKey.value = sug;
        search();
    } else {
        isNeedShowSug.value = true; // 需要刷新sug
        searchKey.value = sug;
        searchInput.value.focus();
    }
}
const inputFocus = () => {
    searchFocus.value = true;
    isNeedShowSug.value = true; // 需要展示搜索建议
    getSug();
}
const inputBlur = () => {
    //  alert('inputBlur');
    searchFocus.value = false;
    isNeedShowSug.value = false;
    setTimeout(() => {
        // 防止立刻隐藏后，导致的 sugClick 触发不了
        // this.isNeedShowSug = false;
    }, 300);
}
const setSearchEngine = (index) => {
    searchEngineList.forEach(item => {
        item.isDefault = false;
    })
    searchEngineList[index].isDefault = true;
}

const search = () => {
    // 移除焦点
    // this.searchEngineShow = false; // 取消展示搜索引擎
    // this.isNeedShowSug = false; // 不需要展示搜索建议
    // this.$refs.searchInput.blur();

    // window.open(this.searchEngineList[this.searchEngineIndex].url.replace("%s", this.searchKey));

    const searchEngineDefault = searchEngineList.filter(item => item.isDefault);
    go2Link(searchEngineDefault[0].url.replace("%s", searchKey.value));

    if (searchKey.value !== '' && hisSwitch) {
        const searchKeyIdx = searchHistory.value.findIndex(item => item.word === searchKey.value)
        if (searchKeyIdx == -1) {
            // 最多存储 6 个
            if (searchHistory.value.length > 5) {
                searchHistory.value.splice(searchHistory.value.length - 1, 1);
            }
        } else {
            // exits set first
            console.log('exits set first')
            searchHistory.value.splice(searchKeyIdx, 1)
        }
        searchHistory.value.splice(0, 0, {
            uuid: generateUUID(),
            word: searchKey.value
        });
    }
    searchKey.value = '';

    // setTimeout(() => {
    //     this.searchKey = '';
    //     // document.querySelector('#searchInput').focus();
    // }, 500);
}

const clear = ref()
watch((searchKey), () => {
    // isNeedShowSug.value && getSug();
    if (isNeedShowSug.value) {
        getSug();
    }
    let style = clear.value.style;
    if (searchKey.value !== '') {
        // style.visibility = 'unset';
        style.display = 'flex';
    } else {
        // style.display = 'hidden';
        style.display = 'none';
    }

})

watch((searchFocus), () => {
    let bgbox = document.querySelector('.bgbox');

    if (searchFocus.value) {
        // animated pulse
        bgbox.style.transform = 'scale(1.1)';
        // backdrop-blur-sm
        bgbox.style.filter = 'blur(10px)';
        // bgbox.classList.add('backdrop-blur')
        // this.$refs.searchRow.style.backdropFilter = 'unset';
    } else {
        bgbox.style.transform = 'unset';
        bgbox.style.filter = 'unset';
        // bgbox.classList.remove('backdrop-blur')
        // this.$refs.searchRow.style.backdropFilter = 'blur(2px)';
    }
})



</script>

<template>
    <div class="box-border fixed inset-x-4 top-24 md:top-40 max-w-prose m-auto">

        <div class="flex justify-center items-center h-24 mb-2" ref="logo">
            <!-- <img v-show="logoShowType == 'url' && url !== ''" :src="url"
                class="h-full cursor-pointer transition transform-gpu hover:-translate-y-2" @click="favoShow = true" />
            <span v-show="logoShowType == 'time'"
                class="text-6xl cursor-pointer transition hover:-translate-y-1" @click="favoShow = true">{{
                    time }}</span> -->
                    <!-- logoShowType == 'weather' -->
            <!-- <Weather class="weather"></Weather> -->
        </div>

        <div ref="searchForm">
            <!-- 'visible' : 'invisible' -->
            <div :class="`flex space-x-0.5 h-8 ${searchFocus ? 'visible' : 'invisible'}`">
                <div v-for="(item, index) in searchEngineList" :key="item.uuid" :index="index"
                    :class="`flex space-x-0.5 items-center bg-white px-2 py-1 cursor-pointer hover:bg-white transition
                       border-l border-t border-gray-50 border-opacity-10 rounded-tl-md rounded-tr ${item.isDefault ? '' : 'bg-opacity-20'}`" @click="setSearchEngine(index)">
                    <img v-show="isNotEmpty(item.icon)" :src="item.icon" class="w-4 h-4" />
                    <span class="text-sm">{{ item.name }}</span>
                </div>
            </div>
            <!-- backdrop-blur-sm -->
            <div :class="`w-full border-2 border-gray-50 border-opacity-10 shadow-xl rounded-md  flex bg-white
                 ${searchFocus ? 'rounded-tl-none' : 'bg-opacity-20'}`" ref="searchRow">
                <div class="w-full">
                    <input type="text" class="p-2 outline-none bg-transparent w-full" spellcheck="false" id="searchInput"
                        ref="searchInput" @keyup.enter="search()" @focus="inputFocus" v-model="searchKey">
                </div>
                <div class="w-5 justify-center items-center text-lg cursor-pointer hidden" ref="clear">
                    <i class="fas fa-times" @click="searchKey = '', searchInput.focus();"></i>
                </div>
                <div class="w-10 flex justify-center items-center text-lg cursor-pointer">
                    <i class="fa fa-search" @click="search()"></i>
                </div>
            </div>
            <ul v-show="suggestionShow"
                class="block mt-1 border border-gray-50 border-opacity-10 shadow-xl rounded-md bg-white divide-y divide-gray-200 divide-dashed">
                <li v-for="(item, index) in suggestion" :key="item.uuid" :index="index"
                    class="flex text-sm cursor-pointer h-12">
                    <div @click="sugClick(item.orgSug, true)"
                        class="w-full transition hover:bg-green-500 rounded-md h-full flex items-center pl-3">
                        <i class="fa fa-history" aria-hidden="true" v-if="item.isHis" />
                        <span v-html="item.sug" class="text-sm antialiased ml-2"></span>
                    </div>
                    <div @click="sugClick(item.orgSug, false)"
                        class="w-10 ml-1 grid grid-cols-1 place-content-center place-items-center transition hover:bg-green-500 rounded-md">
                        <i class="fa fa-pencil-alt" aria-hidden="true"></i>
                    </div>
                </li>

                <li class="flex justify-center items-center	cursor-pointer rounded-md hover:bg-green-500"
                    @click="clearSearchHis()" v-show="searchKey === '' && hisSwitch">
                    <i class="fas fa-trash-alt" aria-hidden="true" style="font-size: 15px;"></i>
                    <span class="ml-2">清空</span>
                </li>
            </ul>
        </div>

        <transition enter-active-class="animate__animated animate__fadeInUp animate__faster"
            leave-active-class="animate__animated animate__fadeOutDown animate__faster">
            <Guide v-show="!searchFocus"></Guide>
        </transition>

        <!-- <h-pop :show="favoShow" @close="favoShow = false" :style-set="{ top: '10%', maxWidth: '800px' }"
            :footerShow="false">
            <template #header>
                <div>我的收藏</div>
            </template>
            <template #main>
                <IndexSet></IndexSet>
            </template>
        </h-pop> -->

        <transition enter-active-class="animate__animated animate__fadeInUp animate__faster"
            leave-active-class="animate__animated animate__fadeOutDown animate__faster">
            <div v-show="!searchFocus" class="fixed inset-x-2 bottom-2 text-center flex justify-center">
                <div
                    class="bg-white bg-opacity-20 p-1 rounded cursor-pointer transition-all duration-500 ease-linear transform-gpu hover:scale-110 hover:bg-green-200 hover:bg-opacity-50">
                    <span class="italic tracking-widest text-xs md:text-sm">
                        {{ yiyanStr }}
                    </span>
                </div>
            </div>
        </transition>
    </div>
</template>

<style scoped></style>
